/**
 * Created by chenxq on 2017/12/18.
 */
import React,{Component} from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import { Button, Modal,Select,  Steps,Tabs ,Popconfirm,message,Tooltip} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Info from '../../components/Customer/Info';
import Follow from '../../components/Customer/Follow';
import Plan from '../../components/Customer/Plan';
import SignList from '../../components/Customer/SignList';
import AccountList from '../../components/Sign/AccountList';
import DescriptionList from '../../components/DescriptionList';
import {convertLongToString} from '../../utils/index';
import Call from '../../components/Call';
import request from '../../utils/request';
const { Description } = DescriptionList;
const { Step } = Steps;
const ButtonGroup = Button.Group;
const  {Option} =Select;

const tabList=[{
  key: 'customer',
  tab: '客户管理',
}, {
  key: 'sign',
  tab: '签单管理',
},{
  key: 'follow',
  tab: '跟进记录'
},{
  key: 'visit',
  tab: '回访计划'
}];

@connect(state=>({
  customer:state.customer
}))
export default class extends Component{
  constructor(props){
    super(props);
    this.state={
      tabKey:'customer',
      customerId: 0,
      changeVisible:false,
      changeStateValue:0,
      callVisible:false
    }
  }
  getCustomerState(params){
    let str;
    switch(params.state){
      case 'INIT': str=params.type==='PUBLIC'?'公共资源池':'私有资源池'; break;
      case 'FOLLOW' : str='营销客户'; break;
      case 'INTENTION' : str='意向客户'; break;
      case 'MAINTAIN' : str='签约客户'; break;
      case 'LOSE' : str='输单客户'; break;
      case 'SUCCESS' :str="赢单客户"; break;
      case 'INVALID' : str='无效客户'; break;
      default : str='其他';
    }
    return str;
  }
  getContent(){
    let {customer} = this.props;
    let {curInfo} = customer;
    let{lastFollowTime,followerName}= curInfo;
    return (
        <DescriptionList  size="small" col="2">
          <Description term="客户状态">{this.getCustomerState(curInfo)}</Description>
          <Description term="跟进人">{followerName || '暂无'}</Description>
          <Description term="最后跟进时间">{lastFollowTime ? convertLongToString(lastFollowTime) : "" }</Description>
        </DescriptionList>
    )
  }
  // 标记为意向用户
  intend=()=>{
    let customerId= this.state.customerId;
    let {customer} = this.props;
    let {curInfo} = customer;
    request(`/v1/customer/intend/${customerId}`,{
      method:'POST',
      body:{}
    }).then(jsonData=>{
      if(jsonData.result){
        message.success('操作成功',0.8, this.getDetail);
      }else{
        message.error(jsonData.msg || '操作失败')
      }
    })
  }

  // 无效
  invalid=()=>{
    let customerId= this.state.customerId;
    let {customer} = this.props;
    let {curInfo} = customer;
    request(`/v1/customer/invalid`,{
      method:'POST',
      body:[customerId]
    }).then(jsonData=>{
      if(jsonData.result){
        this.getDetail();
      }else{
        message.error(jsonData.msg || '操作失败')
      }
    })
  }
  // 放弃
  quit=()=>{
    let _this=this;
    let customerId= this.state.customerId;
    request(`/v1/customer/quit`,{
      method:'POST',
      body:[customerId]
    }).then(jsonData=>{
      if(jsonData.result){
        message.success('放弃成功',0.8,()=>{
          _this.getDetail();
        })
      }else{
        message.error(jsonData.msg || '放弃失败');
      }
    })
  }



  getAction(){
    let {customer} = this.props;
    let {curInfo,ids} = customer ;
    let {state} =curInfo;

    let id=curInfo.id;
    let length=ids.length;
    let index=ids.indexOf(id);
    let nextIndex=length>(index+1) ? index+1 : -1;

    return <div className="flex-row" style={{justifyContent:"flex-end"}}>
      <Tooltip placement="top" title="返回">
      <Button style={{marginRight:20}} shape="circle" icon="arrow-left" onClick={()=>{window.history.go(-1)}}/>
      </Tooltip>

      {nextIndex>0 &&
      <Tooltip placement="top" title="下一个 客户">
      <Button style={{marginRight:20}} shape="circle" icon="arrow-right" onClick={this.goAnotherDetail.bind(this,nextIndex)}/>
      </Tooltip>
        }

      {['FOLLOW'].indexOf(state)>=0 && <Button type="primary" onClick={this.intend}>意向</Button>}
      {['INVALID','LOSE','INIT'].indexOf(state)<0 &&<Popconfirm title="确定要将放弃该客户" onConfirm={this.quit}><Button type="danger">放弃</Button></Popconfirm>}
      {['INVALID','INIT'].indexOf(state)<0 && <Popconfirm title="确定要将该客户标记为无效" onConfirm={this.invalid}><Button>无效</Button></Popconfirm>}
      {['LOSE'].indexOf(state)>=0 && <Button onClick={this.changeState}>划转</Button>}
      {['INIT'].indexOf(state)<0 && <Button type="primary" icon="phone" style={{backgroundColor:"#29c566",borderColor: "#29c566"}} onClick={this.changeCallVisible.bind(this,true)}>拨打电话</Button>}
    </div>
  }

  changeCallVisible=(visible)=>{
    this.setState({
      callVisible:visible
    })
  }
  onTabChange=(key)=>{
    this.setState({
      tabKey:key
    })
  }
  tabContentList=()=>{return {
    customer: <Info key={this.state.customerId} />,
    sign: <SignPage key={this.state.customerId} />,
    follow:<Follow key={this.state.customerId} />,
    visit:<Plan key={this.state.customerId} />,
  }}
  changeState=()=>{
    this.setState({
      changeVisible:true,
      changeStateValue:0
    })
  }
  changeStateSub=()=>{
    let {changeStateValue,customerId}= this.state;
    let _this=this;
    let params={
      customerIds:[customerId]
    }
    if(changeStateValue){
      params.type=changeStateValue;
    }
    this.props.dispatch({
      type:'customer/fetchShift',
      payload:params
    }).then(jsonData=>{
      if(jsonData.result){
        message.success('划转成功',0.8,()=>{
          _this.getDetail();
        })
      }else{
        message.error(jsonData.msg || '划转失败');
      }
    })
  }
  getDetail=()=>{
    let {customerId} = this.state;
    this.props.dispatch({
      type:'customer/fetchCustomerDetail',
      payload:customerId
    })
  }
  componentDidMount(){
    let {params} = this.props.match;
    if(!params.id){
      message.error('参数有误');
      return ;
    }
    this.setState({
      customerId:params.id
    },()=>{
      this.getDetail();
    });
  }
  componentWillReceiveProps(nextProps){
    //console.log(nextProps.match,this.props.match,"next")
    let {params} = this.props.match;
    if(!params.id){
      message.error('参数有误');
      return ;
    }
    let nextParams=nextProps.match.params;
    if(nextParams.id != params.id){
      this.setState({
        customerId:nextParams.id
      },()=>{
        this.getDetail();
      });
    }
  }
  getTitle=()=>{
    let {customer} = this.props;
    let {curInfo,ids} = customer ;
    let baseInfo=curInfo.info || {};
    let id=curInfo.id;
    let length=ids.length;
    let index=ids.indexOf(id);
    let lastIndex=index-1;
    let nextIndex=length>(index+1) ? index+1 : -1;
    return (<div >
      <span style={{marginRight:30}}>{baseInfo.name}</span>
      {/*{lastIndex>=0 && <Button style={{marginRight:20}} onClick={this.goAnotherDetail.bind(this,lastIndex)}>上一位</Button>}*/}
      {/*{nextIndex>0 && <Button onClick={this.goAnotherDetail.bind(this,nextIndex)}>下一位</Button>}*/}
    </div>)
  }
  goAnotherDetail=(index)=>{
    let {customer} = this.props;
    let {ids} = customer ;
    if(ids[index]){
      this.props.history.push('/empty');
      setTimeout(() => {
        this.props.history.replace(`/customer/detail/${ids[index]}`);
      });
      //this.props.history.push(`/customer/detail/${ids[index]}`);
      // by chenxq 同一个url 不同参数 react-router检测不到更新  导致页面未跳转 componentWillReceiveProps 亦不执行 暂时用上面的粗暴办法 以后改进
      return ;
    };
    message.error('客户id 有误');
  }
  render(){
    let {tabKey} = this.state;
    let {customer} = this.props;
    let {curInfo} = customer ;
    let baseInfo=curInfo.info || {};

    return (<PageHeaderLayout title={this.getTitle()}
                              content={this.getContent()}
                              action={this.getAction()}
                              tabList={tabList}
                              onTabChange={this.onTabChange}
    >
      <div>
        {this.tabContentList()[tabKey]}
        {
          'LOSE' === curInfo.state && <Modal title="划转回归池"
                                             onOk={this.changeStateSub}
                                             onCancel={()=>{
                                               this.setState({
                                                 changeVisible:false
                                               })
                                             }}
                                             visible={this.state.changeVisible}
          >
            <div className="flex-row flex-aCenter">
              <div style={{width:'60px'}}>回归池:</div>
              <Select value={this.state.changeStateValue || 0} onChange={(val)=>{
                this.setState({
                  changeStateValue:val
                })
              }
              } style={{width:'120px'}}>
                <Option value={0} >初始池</Option>
                <Option value={1}>公共资源池</Option>
                <Option value={2}>私有资源池</Option>
              </Select>
            </div>
          </Modal>
        }
        {this.state.callVisible && <Call customerInfo={curInfo} onChangeVisible={this.changeCallVisible}/>}
      </div>

    </PageHeaderLayout>)
  }
}


const TabPane = Tabs.TabPane;
class SignPage extends Component{
  state={
    propKey:this.props.propKey || 'signList'
  }
  callback=(key)=>{
    this.setState({
      propKey:key
    })
  }
  render(){
    return <div style={{backgroundColor:"#fff",padding:"15px"}}>
    <Tabs defaultActiveKey={this.state.propKey}
                 onChange={this.callback}>
      <TabPane tab="签单列表" key={'signList'}><SignList/></TabPane>
      <TabPane tab="收支列表" key={'list'}><AccountList type={1}/></TabPane>
    </Tabs>
    </div>
  }
}
